import { GroupDropIndicator } from "@atlaskit/pragmatic-drag-and-drop-react-drop-indicator/group";
import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine";
import {
  dropTargetForElements,
  monitorForElements,
  type ElementDropTargetEventBasePayload,
} from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
import { useEffect, useRef, useState } from "react";

type DropTargetState = "is-innermost-over" | "idle";
const TreeExample = () => {
  const groupRef = useRef<HTMLDivElement | null>(null);

  /** 防止目标状态 */
  const [dropTargetState, setDropTargetState] =
    useState<DropTargetState>("idle");

  useEffect(() => {
    const onDropTargetChange = (payload: ElementDropTargetEventBasePayload) => {
      const { location, self } = payload;

      const [innerMost] = location.current.dropTargets.filter(
        (dropTarget) => dropTarget.data.type === "group"
      );

      setDropTargetState(
        innerMost?.element === self.element ? "is-innermost-over" : "idle"
      );
    };

    const cleanFn = combine(
      monitorForElements({
        canMonitor: ({ source }) => {
          console.log("canMonitor", source);
          return true;
        },
        onDrop: ({ source, location }) => {
          console.log("onDrop", source, location);
        },
      }),
      dropTargetForElements({
        element: groupRef.current!,
        canDrop: ({ source }) => {
          return true;
        },
        getData: () => {
          return {};
        },
        onDragStart: onDropTargetChange,
        onDropTargetChange: onDropTargetChange,
        onDragLeave: () => setDropTargetState("idle"),
        onDrop: () => setDropTargetState("idle"),
      })
    );

    return cleanFn;
  }, []);
  return (
    <GroupDropIndicator
      isActive={dropTargetState === "is-innermost-over"}
      ref={groupRef}
    >
      <div>Tree Example.</div>
    </GroupDropIndicator>
  );
};

export default TreeExample;
